<?php

class ForDeliveryController extends BaseController {

	// Table
	public $table = 'order';

	// Eloquent Model
	public $model = 'Order';

	// Base Route
	public $base = 'for-delivery';

	// Localization
	public $local = 'en';

	// Language Name
	public $language = 'for-delivery';

	// Breadcrumbs
	public $breadcrumbs = [ ['link' => 'for-delivery' , 'title' => 'For Delivery'] ];

	// Set List Data - Input, Object
	public function setListData($data, $object) {
		// Sub-Query that get the total count of Received Order Products under Order 
		$sub1 = OrderProduct::whereRaw( 'ORDER_id = order.id AND order_product.archived = 0 AND order_product.status IN ( ' . Constant::ORDER_RECEIVED . ',' . Constant::ORDER_FOR_DELIVERY .' )' )->select( DB::raw('COUNT(*) AS `count`') );

		// Sub-Query that get the total count of Order Products under Order
		$sub2 = OrderProduct::whereRaw( 'ORDER_id = order.id AND order_product.archived = 0 AND order_product.status NOT IN ( ' . Constant::ORDER_CANCELLED . ' )'  )->select( DB::raw('COUNT(*) AS `count`') );

		// Check if the total number of Received Order Products is equal to total number of Order Products under Order
		$object = $object->whereRaw( ' ( ' . $sub1->toSql() . ' ) = ( ' . $sub2->toSql(). ' )' );

		// Check if total number Order Products under Order is Greater than 0
		$object = $object->whereRaw( ' (' . $sub2->toSql() . ') > 0' );
		
		//$update = $object->lists('id');
		
		if( !empty($data['filter_order_id']) )
			$object = $object->where('id', '=', $data['filter_order_id']);
	
		//$this->_updateStatus( $update );
		
		return $object;
	}
	
	public function addListData( $data ) {
		$update_status = $this->model->where('status','<>', Constant::ORDER_FOR_DELIVERY);
		$order_ids = $update_status->lists('id');
		
		if( $update_status->count() ){
			# API : UPDATE ORDER PRODUCT STATUS FROM RECEIVED TO FOR DELIVERY
			OrderProduct::where('status','<>', Constant::ORDER_FOR_DELIVERY)
				->whereIn('ORDER_id', $order_ids)
				->update(array('status'=> Constant::ORDER_FOR_DELIVERY));
			
			# API : UPDATE ORDER STATUS FROM RECEIVED TO FOR DELIVERY
			Order::whereIn('id', $order_ids)->update(array('status'=> Constant::ORDER_FOR_DELIVERY));
		}
	
		return $data;
	}

	/*private function _updateStatus( $ids ){
	
		$update_status = Order::whereIn('id', $ids)->where('status','<>', Constant::ORDER_FOR_DELIVERY);
		$order_ids = $update_status->lists('id');
		if( $update_status->count() ){
			OrderProduct::where('status','<>', Constant::ORDER_FOR_DELIVERY)
				->whereIn('ORDER_id', $order_ids)
				->update(array('status'=> Constant::ORDER_FOR_DELIVERY));
				
			Order::whereIn('id', $order_ids)->update(array('status'=> Constant::ORDER_FOR_DELIVERY));
		}
	}*/
	
	// Process before storing data
	public function preStore($data) {

		// Updated At Rules
		$this->rules['updated_at'][] = 'required';

		if($data['updated_at'] == '') {
			$this->error['updated_at'][] = 'Please Enter Updated At Field';
		}

		return $data;
	}


	// Process before updating data
	public function preUpdate($data) {

		// Updated At Rules
		$this->rules['updated_at'][] = 'required';

		if($data['updated_at'] == '') {
			$this->error['updated_at'][] = 'Please Enter Updated At Field';
		}
		
		return $data;
	}
	
	// Process before updating data
	public function generatePicklist() {
		// Get Offset
		$load = Asset::load( Input::get('filename') );

		// Get Result Set
		$ids = explode(',', Input::get('order_product_ids') );

		$order = OrderProduct::select('order_product.id', 'order_product.ORDER_id','order_product.name','order_product.model',
				'vendor.name as vendor_name',
			'order_to_set.unit', 'order_to_set.street', 'order_to_set.barangay', 'order_to_set.city', 'order_to_set.zip_code', 'order_to_set.mobile')
			->join( 'product', 'order_product.PRODUCT_id', '=', 'product.id' )
			->join( 'product_vendor', 'product.id', '=', 'product_vendor.PRODUCT_id' )
			->join( 'vendor', 'product_vendor.VENDOR_id', '=', 'vendor.id' )
			->leftJoin( 'order_to_set', function ( $order_set ) {
				$order_set->on('order_to_set.ORDER_id', '=', 'order_product.ORDER_id')
				->on('order_to_set.SET_id', '=', 'order_product.SIZE_id');
			})
		->whereIn('order_product.id', $ids)->take( Constant::FILE_LIMIT )->skip( $load['offset'] );
		
		$result['picklist'] = $order->get();

		// If has pick list
		if( count($result['picklist']->toArray()) > 0) {

			// Queue Result Set
			return Asset::queue( View::make('export.fordelivery_picklist')->with($result), Input::get('filename'), $load );
		}

		// Render Report
		$headers = [ 'Sales Order Id', 'Item Id', 'Vendor', 'Name', 'Model', 'Option' ];

		return Asset::render( Input::get('filename'), $headers, $load['offset'] );
	}
	
	
	public function generateDR( ) {

		$data = Input::get('order_id');
		$get_dr = OrderProduct::select( 'company.name',
			'login.lastname','login.firstname',
			'order_product.quantity','order_product.id','order_product.peso',
			'product.name as product_name',
			'purchase_order.approved_at','purchase_order.approved_by','purchase_order.created_by',
			'order_product_option.option_value','order_product_option.price',
			'order_to_set.address' )
		
		->join( 'order','order.id','=','order_product.ORDER_id' )
		->join( 'company','order.COMPANY_ID','=','company.id' )
		->join( 'login','order.EMPLOYEE_id','=', 'login.id' )
		->join( 'product','order_product.PRODUCT_id','=','product.id' )
		->join( 'purchase_order_product','purchase_order_product.ORDER_PRODUCT_id','=','order_product.id' )
		
		->join( 'purchase_order','purchase_order.id','=','purchase_order_product.PURCHASE_ORDER_id' )
		->leftJoin( 'order_product_option', function ( $order_set ) {
			$order_set->on( 'order_product_option.ORDER_id', '=', 'order_product.ORDER_id' )
			->on( 'order_product_option.PRODUCT_id', '=', 'order_product.PRODUCT_id' );
		})		
		->leftJoin( 'order_to_set', function ( $order_set ) {
			$order_set->on( 'order_to_set.ORDER_id', '=', 'order_product.ORDER_id' )
				->on('order_to_set.SET_id', '=', 'order_product.SIZE_id');
		})
		->where( 'order_product.ORDER_id','=',$data );

		 $generate_dr['generate_dr']=$get_dr->get();
		
		return View::make( 'export.fordelivery_generatedr' )->with( $generate_dr );
	}

	public function postSalesOrderStatus(){
	
		$dir			= Config::get('app.lbea');
		$file			= Input::file('postSalesOrderStatus');
		$moved			= $file->move($dir,$file->getClientOriginalName());
		$uploaded_file	= array();
		$uploaded_data	= array();
		if($moved){
			$uploaded_file = fopen($dir . '/' . Input::file('postSalesOrderStatus')->getClientOriginalName(), 'r');
		}
		if($uploaded_file){
			$c=0;
			$row = 0;
				
			while (($data = fgetcsv($uploaded_file, 1000, ",")) !== FALSE) {
				$num = count($data);
				$row++;
				for ($c=0; $c < $num; $c++) {
					$uploaded_data[$row][] = $data[$c];
				}
			}
		}
		unset($uploaded_data[1]);
		foreach($uploaded_data AS $count_upload => $upload_data){
			$order_product = OrderProduct::find($upload_data[0]);
				
			Backtrack::debug($upload_data);
		}
		exit;
		return [ 'success' => 1 ];
	}

	/**
	 * Retrieve preview list.
	 * @author AngelaMisa 03/12/2015
	 * @return mixed
	 */
	public function getPreviewList( $limit = 5 ) {
		$data['payment_method'] = Constant::getPaymentList( true );
		$data['results'] =  Order::active()
			->where('status', Constant::ORDER_FOR_DELIVERY)
			->orderBy( 'order.created_at', 'DESC')->limit(5)
			->get();
	
		return View::make( 'for-delivery-preview-list' )->with( $data );
	}
}